﻿using System;
using System.Web.UI;
using ASPNETVN.PORTAL.Components.Security;

namespace ASPNETVN.PORTAL.Components.Share.Controls
{
    public partial class PostComment : UserControl
    {
        public bool IsRequireApproved { set; get; }

        // Delegate declaration
        public delegate void PostingHandler(object sender, EventArgs e);
        public delegate void PostedHandler(object sender, EventArgs e);
        // event declaration
        public event PostingHandler Posting;
        public event PostedHandler Posted;

        public string Title { set; get; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Recaptcha1.Validate += Recaptcha1_Validate;
        }

        void Recaptcha1_Validate(object sender, EventArgs e)
        {
            if (Recaptcha1.IsValid)
            {
                if (Posting != null)
                {
                    Posting(sender, e);
                }
                int itemID = Convert.ToInt32(Request.QueryString["itemid"]);
                Guid moduleID = new Guid(Request.QueryString["mid"]);
                if (itemID > 0)
                {
                    Comment comment = new Comment();
                    comment.ModuleID = moduleID;
                    comment.ItemID = itemID;

                    comment.Body = Server.HtmlEncode(TextBoxContent.Text);
                    comment.CreatedBy = TextBoxCreateBy.Text;
                    comment.CreatedDate = DateTime.Now;

                    if (this.IsRequireApproved)
                    {
                        comment.Status = false;
                    }
                    else
                    {
                        comment.Status = true;
                        comment.ApprovedBy = comment.CreatedBy;
                        comment.ApprovedDate = comment.CreatedDate;
                    }

                    comment.Insert();
                    TextBoxContent.Text = string.Empty;
                }

                if (Posted != null)
                {
                    Posted(sender, e);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (Request.IsAuthenticated)
                {
                    TextBoxCreateBy.Text = PortalSecurity.CurrentUser.Identity.Email;
                    TextBoxCreateBy.ReadOnly = true;
                }
                TextBoxTitle.Text = this.Title;
            }
        }
    }
}